package mybatis.generator.util;

import java.util.Arrays;
import java.util.List;

import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * @author Rubble
 * @date 2021/8/20
 **/
@Slf4j
public class GenUtil {

  private List<String> skipFields = Arrays.asList("delFlag","createTime","createBy","updateTime","updateBy");


  public String lowerFirst(String name){
    return StrUtil.lowerFirst(name);
  }

  public boolean isDescField(String comment){
    return comment!=null && ( comment.contains("(") || comment.contains("（"));
  }

  public String getDescField(String field,String comment){
    return isDescField(comment)?field+"Desc":field;
  }

  public String getShortComment(String comment){
    if(comment!=null ){
      if(comment.contains("（")||comment.contains("(")){
        String desc = comment.replace("(", "（");
        return desc.substring(0,desc.indexOf("（"));
      }
    }
    return comment;
  }

  public boolean isRequestField(String field){
    return field!=null && !skipFields.contains(field);

  }

  public String buildEnumStr(String field,String comment){
    if(!isDescField(comment)){
      return "";
    }
    if("delFlag".equals(field)){
      return "";
    }
    try {
      comment = comment.replace("(","（").replace(")","）");
      String[] commentSplit = comment.split("（");
      String shortComment =  commentSplit[0];
      String valueComment = commentSplit[1];
      if(valueComment.endsWith("）")){
        valueComment  = valueComment.substring(0,valueComment.lastIndexOf("）"));
      }
      String dataStr = valueComment.replace(";","；")
          .replace(":","：");
      String[] itemArr = dataStr.split("；");


      String enumName = StrUtil.upperFirst(field)+"Enum";
      StringBuilder builder = new StringBuilder();
      String startStr = "@Getter\n"
          + "@AllArgsConstructor\n"
          + "public enum "+enumName+" implements ICommonEnum{\n"
          + "\n";
      builder.append(startStr);
      String commentLine = "  /**\n"
          + "   * "+comment+"\n"
          + "   */\n";
      builder.append(commentLine);
      int count = 0;
      for (String str : itemArr) {
        String[] arr = str.split("：");
        if(arr.length!=2){
          log.info("GenUtil skip attribute comment {}  attr: {}",comment,str);
          continue;
        }
        String strItem = StrUtil.format("  A{}({},\"{}\"),\n",count++,arr[0].trim(),arr[1].trim());
        builder.append(strItem);
      }
      String endStr = "  ;\n"
          + "  int code;\n"
          + "  String desc;\n"
          + "\n"
          + "  public static "+enumName+" getEnumByCode (Integer code) {\n"
          + "    return code!=null?Arrays.stream(values()).filter(e->e.getCode()==code).findFirst().orElse(null):null;\n"
          + "  }\n"
          + "\n"
          + "  public static String getDescByCode (Integer code) {\n"
          + "    return code!=null?Arrays.stream(values()).filter(e->e.getCode()==code).map("+enumName+"::getDesc).findFirst().orElse(null):null;\n"
          + "  }"
          + "\n"
          + "}";
      builder.append(endStr);

      return builder.toString();
    }catch (Exception e){
      log.error("GenUtil build enums error",e);
    }
    return "";
  }

  public String getDescFieldMethod(String entity,String field){
    if("delFlag".equals(field)){
      return "";
    }
    String entityEnum = entity+"Enums";
    String filedEnum = StrUtil.upperFirst(field)+"Enum";
    String getMethodStr = "\n"
        + "  public String get"+StrUtil.upperFirst(field)+"Desc () {\n"
        + "    return "+entityEnum+"."+filedEnum+".getDescByCode("+field+");\n"
        + "  }";
    return getMethodStr;
  }

}
